package com.h3bpm.starcharge.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.starcharge.common.bean.WorkflowComment;
import com.h3bpm.starcharge.common.uitl.SqlUtils;
import com.h3bpm.starcharge.service.impl.WorkflowCommentServiceImpl;
import data.DataTable;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Controller
@RequestMapping("/starCharge/fileDownController")
public class FileDownController extends ControllerBase {


    @RequestMapping(value = "/downloadPDF", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object downloadPDF(String fileUrl, HttpServletResponse response) {
        try {
            String realPath = this.request.getSession().getServletContext().getRealPath("/");
            String savePath = realPath + fileUrl;
            String fileName = savePath.substring(savePath.lastIndexOf("/") + 1);//获取要下载的文件名
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Content-Type", "application/octet-stream");
            InputStream in = new FileInputStream(savePath);//获取文件输入流
            int len = 0;
            byte[] buffer = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);//将缓冲区的数据输出到客户端浏览器
            }
            in.close();

            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/download")
    @ResponseBody
    public Object downloadTest(@RequestParam String fileName, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Type", "application/octet-stream");
            Resource resource = new ClassPathResource(fileName);
            File myFile = resource.getFile();
            InputStream in = new FileInputStream(myFile);
            int len = 0;
            byte[] buffer = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);//将缓冲区的数据输出到客户端浏览器
            }
            in.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/importUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResBody importUser() {
        ResBody result = ResBody.buildFailResBody();
        String querySql = "SELECT * from import_user";
        try {
            DataTable dataTable = SqlUtils.doQuery(querySql);

            if (dataTable.getRows().size() > 0) {

                for (int i = 0; i < dataTable.getRows().size(); i++) {
                    User user = AppUtility.getEngine().getOrganization().GetUserByCode(dataTable.getRows().get(i).getString("mobile"));
                    if (user == null) {
                        user = new User();
                        user.setCode(dataTable.getRows().get(i).getString("mobile"));
                        user.setMobile(dataTable.getRows().get(i).getString("mobile"));
                        user.setObjectID(UUID.randomUUID().toString());
                        user.setName(dataTable.getRows().get(i).getString("name"));
                        user.setDingTalkAccount(dataTable.getRows().get(i).getString("dingtalkid"));
                        user.setParentID(dataTable.getRows().get(i).getString("parentid"));
                        user.setIDNumber(dataTable.getRows().get(i).getString("idnumber"));
                        AppUtility.getEngine().getOrganization().AddUnit(User.AdministratorAlias, user);
                    }


                }

            }
            result = ResBody.buildSuccessResBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void test() {
        WorkflowCommentServiceImpl workflowCommentService = new WorkflowCommentServiceImpl();
        WorkflowComment workflowComment = new WorkflowComment();
        workflowComment.setUserId("18f923a7-5a5e-426d-94ae-a55ad1a4b239");
        workflowComment.setUserName("系统管理员");
        workflowComment.setInstanceId("6f0e7d60-7119-4fd8-9d1d-73f1f78ef613");
        workflowComment.setWorkItemId("05931697-6c53-498a-9031-75d386e96296");
        workflowComment.setNotifyUserIds("18f923a7-5a5e-426d-94ae-a55ad1a4b239,cdb4262d-1386-4631-84cd-46360b9e5bde");
        workflowCommentService.sendMsgToUser(workflowComment);
    }

    @Override
    public String getFunctionCode() {
        return null;
    }

    @RequestMapping(value = "/pdfRead", method = RequestMethod.GET)
    public void pdfStreamHandeler(String fileUrl, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String realPath = this.request.getSession().getServletContext().getRealPath("/");
        String savePath = realPath + fileUrl;
        String path = request.getServletContext().getRealPath("/Portal/TempImages/");
        //获取要下载的文件名
        String fileName = savePath.substring(savePath.lastIndexOf("/") + 1);
        try {
            File file = new File(path + "/" + fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment;fileName=test.pdf");
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
